<?php

namespace AppBundle\Controller\Admin;

use AppBundle\Entity\Category;
use AppBundle\Form\CategoryType;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

class CategoryController extends Controller{

  /**
  * @Route("/admin/category/create", name="admin_category_create")
  */
  public function newAction(Request $request){
    $category = new Category();
    $form = $this->createForm(CategoryType::class,$category);

    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){

      // 添加顶级分类
      $em = $this->getDoctrine()->getManager();
      $em->persist($category);
      $em->flush();

      return $this->redirect($this->generateUrl('admin_category_list'));
    }

    return $this->render('admin/category/create.html.twig',array(
      'form' => $form->createView(),
    ));
  }

  /**
  * @Route("admin/category/list",name="admin_category_list")
  */
  public function listAction(Request $request){

    //所有的顶级分类
    $categories=$this->getDoctrine()
          ->getRepository('AppBundle:Category')
          ->getRootNodes();
    return $this->render('admin/category/list.html.twig',array(
      'categories'=>$categories,
    ));
  }

  /**
  * @Route("admin/category/show/{id}",name="admin_category_show")
  * @ParamConverter("category",class="AppBundle:Category")
  */
  public function showAction(Category $category){

      $posts=$category->getBlogPosts();
      return $this->render('admin/category/show.html.twig',array(
        'category' => $category,
        'posts' => $posts,
      ));
  }
}
